import React, { useState } from 'react';
import { Button, Card, message, Space } from 'antd';
import { SendOutlined } from '@ant-design/icons';
import { createStyles } from 'antd-style';
import axios from 'axios';
import { UrlBar, RequestHeader, RequestBody, ResponsePanel, Tabs } from './components';

const useStyles = createStyles(({ token }) => ({
  container: {
    padding: '24px',
  },
  card: {
    marginBottom: '16px',
  },
  sendButton: {
    marginTop: '16px',
  },
}));

interface HeaderItem {
  key: string;
  name: string;
  value: string;
}

const InvokePage: React.FC = () => {
  const { styles } = useStyles();
  const [method, setMethod] = useState('GET');
  const [url, setUrl] = useState('');
  const [headers, setHeaders] = useState<HeaderItem[]>([]);
  const [bodyType, setBodyType] = useState('none');
  const [bodyContent, setBodyContent] = useState('');
  const [activeTab, setActiveTab] = useState('headers');
  const [loading, setLoading] = useState(false);
  const [response, setResponse] = useState<any>({});

  const handleSend = async () => {
    if (!url) {
      message.error('请输入请求URL');
      return;
    }

    try {
      setLoading(true);
      const requestHeaders = headers.reduce((acc, header) => {
        if (header.name && header.value) {
          acc[header.name] = header.value;
        }
        return acc;
      }, {} as Record<string, string>);

      let requestBody: any;
      if (bodyType === 'json') {
        try {
          requestBody = JSON.parse(bodyContent);
        } catch (error) {
          message.error('JSON格式错误');
          return;
        }
      } else if (bodyType !== 'none') {
        requestBody = bodyContent;
      }

      const response = await axios({
        method: method.toLowerCase(),
        url,
        headers: requestHeaders,
        data: requestBody,
      });

      setResponse({
        status: response.status,
        statusText: response.statusText,
        headers: response.headers,
        data: response.data,
      });
    } catch (error: any) {
      if (error.response) {
        setResponse({
          status: error.response.status,
          statusText: error.response.statusText,
          headers: error.response.headers,
          data: error.response.data,
        });
      } else {
        message.error(error.message || '请求失败');
      }
    } finally {
      setLoading(false);
    }
  };

  const tabItems = [
    {
      key: 'headers',
      label: '请求头',
      children: <RequestHeader headers={headers} onHeadersChange={setHeaders} />,
    },
    {
      key: 'params',
      label: '参数',
      children: <RequestHeader headers={headers} onHeadersChange={setHeaders} />,
    },
    {
      key: 'body',
      label: '请求体',
      children: (
        <RequestBody
          bodyType={bodyType}
          bodyContent={bodyContent}
          onBodyTypeChange={setBodyType}
          onBodyContentChange={setBodyContent}
        />
      ),
    },
  ];

  return (
    <div className={styles.container}>
      <Card className={styles.card}>
        <Space direction="vertical" style={{ width: '100%' }}>
          <UrlBar
            method={method}
            url={url}
            onMethodChange={setMethod}
            onUrlChange={setUrl}
            onSend={handleSend}
          />
          <Tabs items={tabItems} activeKey={activeTab} onChange={setActiveTab} />
          <Button
            type="primary"
            icon={<SendOutlined />}
            onClick={handleSend}
            loading={loading}
            className={styles.sendButton}
          >
            发送请求
          </Button>
        </Space>
      </Card>

      <ResponsePanel loading={loading} response={response} />
    </div>
  );
};

export default InvokePage;
